package com.ibm.workplace.wcm.cqplugin.cq;

import java.io.*;
import java.util.*;

import org.eclipse.core.runtime.*;

import com.ibm.workplace.wcm.cqplugin.*;
import com.ibm.workplace.wcm.cqplugin.cqweb.CQHttpTest;
import com.ibm.workplace.wcm.cqplugin.preference.*;
import com.ibm.workplace.wcm.cqplugin.ui.*;
//import com.ibm.sdwb.cmvc.client.api.*;

public class CqDefectSearchEngine implements IBugSearchEngine {
      
    public static final String USER_NAME_WILDCARD = "$username$";
    
    CQHttpTest cqHttp;
    
    IBugInfo[] bugInfo;
    
    //private CmvcConnectionProfile connectionProfile;
    
    public CqDefectSearchEngine() {
        super();
        
        //this.connectionProfile = (CmvcConnectionProfile)connectionProfile;
    }
    
    public CqDefectSearchEngine(IConnectionProfile connectionProfile) {
        super();
        
        //this.connectionProfile = (CmvcConnectionProfile)connectionProfile;
    }

    public IBugInfo[] performSearch(IBugSearchCriteria searchCriteria, IProgressMonitor monitor, IProgressPresenter presenter) {
        //List ret = new ArrayList();

        //CmvcDefectSearchCriteria sc = (CmvcDefectSearchCriteria) searchCriteria;

        /**
         * Report -general DefectView -hopCount 0 -local -select name,compname,originlogin,abstract,priority,pubsImpact,releasename,ownerlogin,state,adddate,levelname,age,assigndate,reference,duplicate,enddate,envname,lastupdate,answer,originarea,originname,ownerarea,ownername,remotefamily,remotename,responsedate,prefix,severity,symptom,phaseFound,phaseInject,target,hasApar,activity,odctrigger,impact,odctarget,deftype,qualifier,content,source,srchistory
         *  -where releasename in ('hats7.0','hats6.0srv') AND ownerlogin in ('smythew') AND state in ('open','working')
         * 
         */
/*
        try {
           CmvcConnection connection = CmvcUtils.getConnection(connectionProfile);
            if (connection.isConnected()) {
                if (presenter != null) {
                    presenter.setProgressStatusText("Performing search...");
                    presenter.setProgressVisible(true);
                    presenter.setProgress(10);
                }

                String name = "ReportGeneral";
                Command cmd = CommandFactory.getInstance().getCommand(name);
                cmd.setFamilyInfo(connection.getFamilyInfo());
                cmd.setSessionData(connection.getSessionData());
                cmd.addObjectSpecValue("DefectView");
                cmd.addParameterValue("-hopCount", "0");
                cmd.addParameterValue("-local");
                //cmd.addParameterValue("-select", "name,compname,originlogin,abstract,priority,releaseName,ownerlogin,state,severity");
                cmd.addParameterValue("-select", CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_DEFECT_NAME_COLUMN) + "," + CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_COMPONENT_COLUMN) + "," + CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_ORIGINATOR_COLUMN) + "," + CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_ABSTRACT_COLUMN) + "," + CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_PRIORITY_COLUMN) + "," + CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_RELEASE_COLUMN) + "," + CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_OWNER_COLUMN) + "," + CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_STATE_COLUMN) + "," + CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_SEVERITY_COLUMN));
                cmd.addParameterValue("-where", sc.isAdvanced() ? (sc.getAdvancedQuery() != null ? sc.getAdvancedQuery() : "") : buildWhere(sc));
                CommandResults rs = CmvcUtils.executeCommand(connectionProfile, cmd);

                if (!monitor.isCanceled() && rs.getReturnCode() == CommandResults.SUCCESS) {
                    monitor.subTask("Getting results...");

                    //System.out.println("messagE: " + rs.getSuccessMessages());
                    String str = rs.getSuccessMessages();
                    //System.out.println("!!!!! entire string: " + str + "!!!!!!!!!11");
                    int numLines = countLines(str);
                    int index = 0;

                    BufferedReader br = new BufferedReader(new StringReader(str));
                    String line = null;
                    while ((line = br.readLine()) != null && ret.size() < 500) {
                        //System.out.println(line);
                        //System.out.println("1: " + System.currentTimeMillis());
                        String[] values = parseCmvcResultLine(line);
                        //System.out.println("2: " + System.currentTimeMillis());
                        if (values.length == 9) {
                            CmvcDefectInfo cdi = new CmvcDefectInfo(values[0], values[3], values[5], values[1], values[6], CmvcUtils.getUserEmailAddress(connectionProfile, values[6]), values[2], CmvcUtils.getUserEmailAddress(connectionProfile, values[2]), values[7], values[4], values[8]);
                            cdi.setConnectionProfile(connectionProfile);
                            //System.out.println("3: " + System.currentTimeMillis());
                            ret.add(cdi);

                        }

                        index++;
                        if (presenter != null) {
                            int numLinesForCalculation = (numLines < 500 ? numLines : 500);
                            presenter.setProgress(10 + ((int) index * 90 / numLinesForCalculation));
                            //presenter.setProgressStatusText("Getting results (" + (index + 1) + " of " + numLines + ")");
                        }

                        if (monitor.isCanceled()) {
                            break;
                        }
                    }
                    br.close();
                } else {
                    BugInfoPluginActivator.getDefault().showErrorMessage("Defect Search (" + connectionProfile.getName() + ")", "An error occurred while searching for defects on " + connectionProfile.getFamily() + ".\n\n" +  CmvcUtils.replaceCrLf("" + rs.getFailureMessages()));
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //if (presenter != null) presenter.setProgressVisible(false);
        }

        return (IBugInfo[]) ret.toArray(new IBugInfo[ret.size()]);

        CqDefectInfo cqDefect = new CqDefectInfo("DFECT00017032");
        cqDefect.setAbstractStr("UI:page navigation works incorrectly when there are more then 1000 documents");
        cqDefect.setComponent("wp.wcm");
        cqDefect.setOriginator("Cassie");
        cqDefect.setOriginatorEmailAddress("lining@cn.ibm.com");
        cqDefect.setOwner("Cassie");
        cqDefect.setOwnerEmailAddress("lining@cn.ibm.com");
        cqDefect.setPriority(BugPriority.HIGH);
        cqDefect.setRelease("6.1");
        cqDefect.setSeverity(BugSeverity.TWO);
        cqDefect.setState(BugState.OPEN);
        //("DFECT00017032","UI:page navigation works incorrectly when there are more then 1000 documents","6.1","wp.wcm","Cassie N Li","lining@cn.ibm.com","Cassie N Li","lining@cn.ibm.com","OPEN","HIGH","TWO")
        return new IBugInfo[] {cqDefect};
*/        

        cqHttp = Activator.cqTest;
        //CqDefectInfo[] defectInfos = null;
        
    	try {
    		if(Activator.DEBUG_ON)
    			System.out.println("1");
			//List<CqDefectInfo> results = cqHttp.queryDefect(searchCriteria);
			Vector results = cqHttp.queryDefect(searchCriteria);
			if(Activator.DEBUG_ON)
				System.out.println("2");
			
			if ((results != null) && (results.size() >0))
			{
				bugInfo = new CqDefectInfo[results.size()];
				for (int i=0; i<results.size(); i++)
				{
					bugInfo[i] = (CqDefectInfo)results.elementAt(i);//results.get(i);
				}
				if(Activator.DEBUG_ON)
					System.out.println(bugInfo[0].toString());
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bugInfo;
		
    }

    private String[] parseCmvcResultLine(String line) {
        if (line == null || line.trim().equals("")) {
            return new String[0];
        } else {
            List ret = new ArrayList();

            int currentStart = 0;
            for (int i = 0; i < line.length(); i++) {
                if (line.charAt(i) == '|') {
                    ret.add(line.substring(currentStart, i));
                    currentStart = i + 1;
                }
            }

            if (currentStart <= line.length() - 1) {
                ret.add(line.substring(currentStart));
            }

            return (String[]) ret.toArray(new String[ret.size()]);
        }
    }
/*    
    public String viewDefectDetail(int i) {
    	
        cqHttp = Activator.cqTest;
        String tempStr;
        
        try {
            tempStr = cqHttp.viewDefectDetail(bugInfo[i].getDefectlink());
        }
        catch(com.ibm.httptest.script.HTMLFailureException e){
        	tempStr = "something wrong with CQHttpTest Moduel, please check your settings.";
        }
        catch(com.ibm.httptest.script.TestFailureException e){
        	tempStr = "something wrong with CQHttpTest Moduel, please check your settings.";
        }

        
        return tempStr;
    	
    }
*/    
/*
    private String buildWhere(CqDefectSearchCriteria sc) {
        List conditions = new ArrayList();

        if (sc.getNumber() != null && !sc.getNumber().trim().equals("")) {
            conditions.add(CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_DEFECT_NAME_COLUMN) + " in " + buildMultiString(sc.getNumber().trim()));
        }

        if (sc.getTarget() != null && !sc.getTarget().trim().equals("")) {
            conditions.add(CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_TARGET_COLUMN) + " in " + buildMultiString(sc.getTarget().trim()));
        }

        if (sc.getOwner() != null && !sc.getOwner().trim().equals("")) {
            String t = performWildcardReplacement(sc.getOwner());
            conditions.add(CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_OWNER_COLUMN) + " in " + buildMultiString(t));
        }

        if (sc.getOriginator() != null && !sc.getOriginator().trim().equals("")) {
            String t = performWildcardReplacement(sc.getOriginator());
            conditions.add(CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_ORIGINATOR_COLUMN) + " in " + buildMultiString(t));
        }

        if (sc.getRelease() != null && !sc.getRelease().trim().equals("")) {
            conditions.add(CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_RELEASE_COLUMN) + " in " + buildMultiString(sc.getRelease()));
        }

        if (sc.getComponent() != null && !sc.getComponent().trim().equals("")) {
            conditions.add(CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_COMPONENT_COLUMN) + " in " + buildMultiString(sc.getComponent()));
        }

        if (sc.getState() != null && !sc.getState().trim().equals("")) {
            conditions.add(CmvcUtils.getCmvcColumnName(CmvcPreferenceConstants.PREF_STATE_COLUMN) + " in " + buildMultiString(sc.getState()));
        }

        if (conditions.size() == 0) {
            return "1=1"; // "releasename in ('hats7.0') AND ownerlogin in ('smythew') AND state in ('open','working')";
        }

        String ret = "";
        for (Iterator it = conditions.iterator(); it.hasNext();) {
            String t = (String) it.next();
            ret = ret + t;
            if (it.hasNext()) {
                ret += " AND ";
            }
        }

        return ret;
    }

    private String buildMultiString(String str) {
        StringBuffer buf = new StringBuffer();
        buf.append("(");
        StringTokenizer st = new StringTokenizer(str, " ");
        while (st.hasMoreElements()) {
            buf.append("'" + st.nextElement() + "'");
            if (st.hasMoreElements()) {
                buf.append(",");
            }
        }

        buf.append(")");
        return buf.toString();
    }

    private static int countLines(String str) {
        StringTokenizer st = new StringTokenizer(str, "\n\r");
        return st.countTokens();
    }

    private String performWildcardReplacement(String str) {
        if (str != null && str.trim().equals(USER_NAME_WILDCARD)) {
            return connectionProfile.getUserName();
        } else {
            return str;
        }
    }
*/    
    public String getBugDetails(String id) {
/*        String val = null;

        try {
            CmvcConnection connection = CmvcUtils.getConnection(connectionProfile);
            if (connection.isConnected()) {
                String name = "DefectView";
                Command cmd = CommandFactory.getInstance().getCommand(name);
                cmd.setFamilyInfo(connection.getFamilyInfo());
                cmd.setSessionData(connection.getSessionData());
                cmd.addObjectSpecValue(id);
                //cmd.addParameterValue(defectNumber);
                cmd.addParameterValue("-long");
                CommandResults rs = CmvcUtils.executeCommand(connectionProfile, cmd);
                //if (rs.getReturnCode() == CommandResults.SUCCESS) {
                val = rs.getMessagesString().trim();
                //} else {
                //   value = rs.get
                //}
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return val;
*/        
        
        cqHttp = Activator.cqTest;
        String tempStr;
        if(Activator.DEBUG_ON)
        	System.out.println("getBugDetails: id: " + id);
        try {
        	if(Activator.DEBUG_ON)
        		System.out.println("enter try");
            tempStr = cqHttp.viewDefectDetail(id);
        }
        catch(com.ibm.httptest.script.HTMLFailureException e){
        	tempStr = "something wrong with CQHttpTest Moduel, please check your settings.";
        }
        catch(com.ibm.httptest.script.TestFailureException e){
        	tempStr = "something wrong with CQHttpTest Moduel, please check your settings.";
        }

        
        return tempStr;
    }


}
